package cn.wuxing.mediation.common.dingding;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.HttpURLConnection;
import javax.net.ssl.HttpsURLConnection;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class MessageSender {

    @SneakyThrows
    public void sendMessage(String title, String content, String sendtime, String receivers,
                             String pcurl, String mobileurl, String token) {
        String url = "https://i.njcit.cn/EIP/sendThirdPartyMsgToPlatform.htm?token=" + token;  // 包含 token 的 URL

        // 构建请求体为 JSON
        JSONObject requestBody = new JSONObject();
        requestBody.put("title", title);
        requestBody.put("content", content);
        requestBody.put("sendtime", sendtime);
        requestBody.put("receivers", receivers);
        requestBody.put("appcode", "cjrh");
        if (pcurl != null) {
            requestBody.put("pcurl", pcurl);
        }
        if (mobileurl != null) {
            requestBody.put("mobileurl", mobileurl);
        }

        // 创建 URL 对象
        URL obj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

        // 如果是 HttpsURLConnection，正确地处理
        if (conn instanceof HttpsURLConnection) {
            ((HttpsURLConnection) conn).setRequestMethod("POST");
            // 设置 SSL 相关属性，或者任何额外安全设置
        } else {
            conn.setRequestMethod("POST");
        }
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setDoOutput(true);

        // 编码参数
        String postData = "param=" + URLEncoder.encode(requestBody.toJSONString(), "UTF-8");

        // 发送 POST 请求
        try (DataOutputStream writer = new DataOutputStream(conn.getOutputStream())) {
            writer.writeBytes(postData);
            writer.flush();
        }

        // 获取响应
        int responseCode = conn.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        // 读取响应内容
        try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            // 输出响应内容
            System.out.println("Response: " + response.toString());
        }

        // 断开连接
        conn.disconnect();
    }
}
